//
//  XLTwoWayMatchingViewController.m
//  XiangLove
//
//  Created by 陈宪栋 on 2018/3/7.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLTwoWayMatchingViewController.h"
#import "XLTwoWayMatchView.h"
 
#import "XLMatchOrderTableViewCell.h"
#import "XLAccountManager.h"
#import <ImSDK/TIMGroupManager.h>
#import <ImSDK/TIMFriendshipManager.h>
#import <ImSDK/ImSDK.h>
#import "IMAMsg.h"
#import "XLHTTPSessionManager+matchOrder.h"
#import "XLHTTPSessionManager+Camgirl.h"
#import "CallMakeViewController.h"
#import "TopUpViewController.h"
#import <ReactiveCocoa.h>
#import <UIViewController+TopViewController.h>
#import "XLNewTopUpView.h"
#import "XLTopUpModel.h"
#import "HomeCallModel.h"

#import "WeixinHelper.h"
#import <StoreKit/StoreKit.h>
#import "BMHStoreObserver.h"
#import "XLHTTPSessionManager+UserInfo.h"
#import "XLTabBarController.h"
#import "XLCardsVucherModel.h"

@interface XLTwoWayMatchingViewController ()<UITableViewDataSource, UITableViewDelegate, XLNewTopUpDelegate>
@property (nonatomic, strong) XLTwoWayMatchView *matchView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *emptyContentView;

@property (nonatomic, strong) NSArray *orderList;

@property (nonatomic, assign) BOOL isRequestMatch;

@property (nonatomic, assign) BOOL isRequestCancelMatch;
@property (nonatomic, assign) NSInteger orderCount;

@property (nonatomic, weak) RACDisposable *requestDisposable;
@property (nonatomic, weak) RACDisposable *matchDisposable;
@property (nonatomic, assign) NSInteger errCount;

@property (nonatomic, copy) NSString *matchId;

@property (nonatomic,strong)XLNewTopUpView      *topUpview;
@property (nonatomic,strong)NSMutableArray      *topUpMoneyArr;
@property (nonatomic,strong)NSMutableArray      *topUpJDArr;
@property (nonatomic,copy  )NSString            *myMoney;
@property (nonatomic,strong)NSDictionary        *zfbDic;
@property (nonatomic,copy  )NSString            *actionType;
@property (nonatomic,copy  )NSString            *payorder;//支付宝订单号
@property (nonatomic,copy  )NSString            *productIds;

@property (nonatomic, assign) BOOL isAppear;
@end

@implementation XLTwoWayMatchingViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    XLTabBarController *tabVC = (XLTabBarController *)self.tabBarController;
//    [tabVC.launchAnimation play];
    [UserDefaults setObject:@"1" forKey:@"tabBarSelectedIndex"];
    [UserDefaults synchronize];
    [self enterObserveGroup];
    [self requestOrderListIsPlay:NO];
    self.isAppear = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.isAppear = NO;
    [self exitObserveGroup];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.orderList = [NSArray array];
    self.zfbDic        = [NSDictionary   dictionary];
    self.topUpMoneyArr = [NSMutableArray array];
    self.topUpJDArr    = [NSMutableArray array];
    [self setupView];
    [self addObserve];
    [self MakeData];
    [self enterObserveGroup];
    [self requestOrderListIsPlay:NO];
}

- (void)setupView {
    self.fd_prefersNavigationBarHidden = YES;
    
    _matchView = [[XLTwoWayMatchView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 240)];
    [_matchView.matchButton addTarget:self action:@selector(matchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_matchView];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.rowHeight = 86;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.tableFooterView = [UIView new];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[XLMatchOrderTableViewCell class] forCellReuseIdentifier:NSStringFromClass([XLMatchOrderTableViewCell class])];
    [self.view addSubview:_tableView];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        _matchView.hidden = YES;
    }else{
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(240, 0, 0, 0));
        }];
        _matchView.hidden = NO;
    }
    
    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 25)];
    headerLabel.textColor = [UIColor darkGrayColor];
    headerLabel.font = [UIFont systemFontOfSize:12];
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
        headerLabel.text = @"他们在找人聊天";
    } else {
        headerLabel.text = @"她们在找人聊天";
        headerLabel.text = @"她们在找人聊天";

    }
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
    [header addSubview:headerLabel];
    _tableView.tableHeaderView = header;
    
    _tableView.hidden = YES;
    
    
    UIView *emptyContentView = [[UIView alloc] init];
    [self.view addSubview:emptyContentView];
    _emptyContentView = emptyContentView;
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {
        [emptyContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
    }else{
        [emptyContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(240, 0, 0, 0));
        }];
    }
    
    UILabel *emptyLabel = [[UILabel alloc] init];
    emptyLabel.font = [UIFont systemFontOfSize:14];
    emptyLabel.textColor = HEXCOLOR(0x9395a2);
    emptyLabel.text = @"暂无人发起视聊";
    [emptyContentView addSubview:emptyLabel];
    [emptyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(emptyContentView);
    }];
    
    UIImageView *emptyImageView = [[UIImageView alloc] init];
    emptyImageView.image = [UIImage imageNamed:@"pic_shiliao_n"];
    [emptyContentView addSubview:emptyImageView];
    [emptyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(72, 52));
        make.centerX.equalTo(emptyContentView);
        make.bottom.equalTo(emptyLabel.mas_top).offset(-12);
    }];
    
    UIButton *gotoDiscoverBtn = [[UIButton alloc] init];
    gotoDiscoverBtn.layer.masksToBounds = YES;
    gotoDiscoverBtn.layer.cornerRadius = 18;
    gotoDiscoverBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
        [gotoDiscoverBtn setTitle:@"去找帅哥" forState:UIControlStateNormal];
    } else {
        [gotoDiscoverBtn setTitle:@"去找美女" forState:UIControlStateNormal];
    }
    [gotoDiscoverBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [gotoDiscoverBtn setBackgroundColor:RGB_HEX(0xFFBB01)];
    [gotoDiscoverBtn addTarget:self action:@selector(gotoDiscover) forControlEvents:UIControlEventTouchUpInside];
    [emptyContentView addSubview:gotoDiscoverBtn];
    [gotoDiscoverBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(160, 36));
        make.centerX.equalTo(emptyContentView);
        make.top.equalTo(emptyLabel.mas_bottom).offset(50);
    }];
    
    emptyContentView.hidden = YES;
}

- (void)addObserve {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForegroundNotification) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBackgroundNotification) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CallOrderExtNotification:) name:@"CallOrderExt" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callNotification) name:@"callreceive" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callNotification) name:@"makecall" object:nil];
    
    @weakify(self);
    [RACObserve(self, orderCount) subscribeNext:^(id x) {
        @strongify(self);
        XLTabBarController *tabVC = (XLTabBarController *)self.tabBarController;
        if ([x integerValue] > 0) {
            [tabVC showBadgeOnItemIndex:1];
        } else {
            [tabVC hideBadgeOnItemIndex:1];
        }
    }];
}

- (void)callNotification {
    self.isRequestMatch = NO;
    [self cancelMatch];
}

- (void)enterForegroundNotification {
    [self enterObserveGroup];
}

- (void)enterBackgroundNotification {//进入后台退出群组
    if ([[XLAccountManager shareInstance]model] != nil) {
        self.isRequestMatch = NO;
        [self cancelMatch];
        [self exitObserveGroup];
    }
}

- (void)CallOrderExtNotification:(NSNotification *)notification {
    TIMMessage *msg = notification.object;
    TIMCustomElem *elem = (TIMCustomElem *)[msg getElem:0];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:elem.data options:0 error:nil];
    id eventId = dic[@"event"];
    if ([eventId integerValue] == 1) { //新订单
        if ([[[msg getConversation] getReceiver] isEqualToString:MatchGroupId1] && [[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
            [self requestOrderListIsPlay:YES];
        }
        if ([[[msg getConversation] getReceiver] isEqualToString:MatchGroupId2] && [[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"]) {
            [self requestOrderListIsPlay:YES];
        }
    } else if ([eventId integerValue] == 2) {  //取消订单
        NSString *hostUserId = dic[@"hostUserId"];
        NSDictionary *hostDic = nil;
        for (NSDictionary *dic in self.orderList) {
            if ([hostUserId isEqualToString:F(@"%@", dic[@"UserId"])]) {
                hostDic = dic;
                break;
            }
        }
        if (hostDic) {
            NSMutableArray *array = self.orderList.mutableCopy;
            [array removeObject:hostDic];
            self.orderList = array.copy;
            self.orderCount = self.orderList.count;
            if (self.orderList.count == 0) {
                self.tableView.hidden = YES;
                self.emptyContentView.hidden = NO;
            } else {
                self.tableView.hidden = NO;
                self.emptyContentView.hidden = YES;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
    } else if ([eventId integerValue] == 3) {  //抢订单
        [self requestOrderListIsPlay:NO];
    } else {
        if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {  //主播
            
        } else {
            @weakify(self);
            [[[XLHTTPSessionManager sharedManager] makeCallWithAnchorId:msg.sender userId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
                @strongify(self);
                HomeCallModel *model = x;
                NSString *callID =  F(@"%@", model.CallId);
                CallMakeViewController *make = [[CallMakeViewController alloc] init];//拔打电话
                make.IsOneTimeCall = model.IsOneTimeCall;
                make.UserFreeSecond = model.UserCardSecond;
                make.peerId = [NSString stringWithFormat:@"%@",msg.sender];
                make.headStr = dic[@"headimg"];
                make.nickNameStr = dic[@"name"];
                make.detailStr = [NSString stringWithFormat:@"%@ %@",dic[@"address"],dic[@"job"]];
                make.addressStr = dic[@"address"];
                make.ageStr = [dic[@"age"] integerValue];
                make.jobStr = dic[@"job"];
                make.ismic = YES;
                make.iscinema = YES;
                make.callid = callID;
                make.videoid = [NSString stringWithFormat:@"%@",callID];
                make.moneyStr = @"50";
                make.gradeStr = [NSString stringWithFormat:@"%@",dic[@"leval"]];
                make.isAuto = YES;
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:make animated:YES completion:nil];
                self.isRequestMatch = NO;
                [self cancelMatch];
                
            } error:^(NSError *error) {
                @strongify(self);
                NSLog(@"%@", error);
                self.isRequestMatch = NO;
                [self cancelMatch];
                if (error.code == 6) {  //余额不足
                    self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
                    self.topUpview.delegate = self;
                    [self.view addSubview:self.topUpview];
                    
                } else if (error.code == -4) {  //被拉入黑名单
                    [HelpTool startTipViewWithText:@"已成为黑名单用户" duration:2.0f type:kTipViewTypeNone];
                } else if (error.code == -3) {  //对方已屏蔽视聊
                    [HelpTool startTipViewWithText:@"对方取消了视频通话功能" duration:2.0f type:kTipViewTypeNone];
                    IMAMsg *msgs = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
                    IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:[NSString stringWithFormat:@"%@",msg.sender]];
                    [conversation sendMessage:msgs completion:^(NSArray *imamsgList, BOOL succ, int code) {
                    }];
                } else {  //创建失败
                   [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
                }
            }];
        }
    }
}

- (void)playSound {
    if (![[UIViewController topViewController] isKindOfClass:NSClassFromString(@"CallMakeViewController")] && ![[UIViewController topViewController] isKindOfClass:NSClassFromString(@"CallRecvViewController")] && [UIApplication sharedApplication].applicationState == UIApplicationStateActive && self.isAppear) {
        SystemSoundID soundID;
        NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"noticeAudio" ofType:@"wav"];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:soundFile], &soundID);
        AudioServicesPlaySystemSound(soundID);
    }
}

#pragma mark - Action
- (void)matchAction:(UIButton *)btn {
    if (btn.selected) {
        [self cancelMatch];
    } else {
        [self gotoMatch];
    }
}

#pragma mark --  开始求伴点击方法
- (void)gotoMatch {
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"] && [[[XLAccountManager shareInstance] model].AccountBalanceString floatValue] < 50) {
        NSDictionary *dic = @{
                              @"userId":[[XLAccountManager shareInstance] model].Id,
                              @"pageIndex":@(1),
                              @"pageSize":@"20"
                              };
        
        [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/Card/GetUserCards" parameters:dic resultClass:[XLCardsVucherModel class]] subscribeNext:^(id x) {
            NSArray * ary = (NSArray *)x;
            for (XLCardsVucherModel * model in ary) {
                if([model.Type integerValue] == 1)
                {
                    if([model.Count integerValue] > 0)
                    {
                        return;
                    }
                }
            }
            self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
            self.topUpview.delegate = self;
            [self.view addSubview:self.topUpview];
            return;
            
            
        } error:^(NSError *error) {
            self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
            self.topUpview.delegate = self;
            [self.view addSubview:self.topUpview];
            return;
        }];
    }
    if ([self checkCameraAuthorization] && [self checkMicroPhoneAuthorization]) {
        if (self.isRequestCancelMatch) {
            [MBProgressHUD showContent:@"操作频繁，请稍后再试" toView:self.view];
            return;
        }
        if (self.isRequestMatch == NO) {
            self.isRequestMatch = YES;
            self.matchView.matchButton.selected = YES;
            [_matchView beginAnimate];
            [self requestMatch];
        }
    }
}

- (void)cancelMatch {
    if (self.isRequestMatch) {
        [MBProgressHUD showContent:@"操作频繁，请稍后再试" toView:self.view];
        return;
    }
    if (self.isRequestCancelMatch == NO) {
        self.isRequestCancelMatch = YES;
        self.matchView.matchButton.selected = NO;
        [_matchView stopAnimate];
        [self exitMatch];
    }
}

- (void)gotoDiscover {
    self.tabBarController.selectedIndex = 0;
}

- (void)requestOrderListIsPlay:(BOOL)isPlay {
    [self.requestDisposable dispose];
    self.requestDisposable = [[[XLHTTPSessionManager sharedManager] getOrderListWithAnchorId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(NSArray *x) {
        self.errCount = 0;
        [MBProgressHUD hideHUDForView:self.tableView];
        //        "UserId": 448859,
        //        "ImgUrl": "http://p001.baomihua.com/345958f7-6120-43fb-8b72-fca3b4b2326b.jpg",
        //        "NickName": "test栋",
        //        "MatchId": "55b90900543b4796a9e70f7acba325be"
        self.orderList = [x copy];
        self.orderCount = self.orderList.count;
        if ([self.orderList isKindOfClass:[NSArray class]] && self.orderList.count > 0) {
            self.tableView.hidden = NO;
            self.emptyContentView.hidden = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
            if (isPlay) {
                [self playSound];
            }
        } else {
            self.tableView.hidden = YES;
            self.emptyContentView.hidden = NO;
        }
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.tableView];
        if (self.errCount <= 5) {
            self.errCount++;
            [self requestOrderListIsPlay:isPlay];
        } else {
            self.errCount = 0;
        }
    }];
}

- (void)requestMatch {
    self.matchDisposable = [[[XLHTTPSessionManager sharedManager] requestMatchingWithUserId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        if ([[x objectForKey:@"result"] boolValue]) {
            self.matchId = x[@"matchId"];
            [self enterMatchGroup];
        } else {
            [MBProgressHUD showContent:x[@"msg"] ?: @"匹配失败，请稍后再试" toView:self.view];
            self.isRequestMatch = NO;
            [self cancelMatch];
        }
    } error:^(NSError *error) {
        [MBProgressHUD showContent:@"匹配失败，请稍后再试" toView:self.view];
        self.isRequestMatch = NO;
        [self cancelMatch];
    }];
}

- (void)exitMatch {
    [[[XLHTTPSessionManager sharedManager] quitMatchingWithUserId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        [self exitMatchGroup];
    } error:^(NSError *error) {
        [self exitMatchGroup];
    }];
}

#pragma mark --- 点击抢单 方法
- (void)dialAction:(UIButton *)btn {
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"] && [[[XLAccountManager shareInstance] model].AccountBalanceString floatValue] < 50) {
        NSDictionary *dic = @{
                              @"userId":[[XLAccountManager shareInstance] model].Id,
                              @"pageIndex":@(1),
                              @"pageSize":@"20"
                              };
        
        [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/Card/GetUserCards" parameters:dic resultClass:[XLCardsVucherModel class]] subscribeNext:^(id x) {
            NSArray * ary = (NSArray *)x;
            for (XLCardsVucherModel * model in ary) {
                if([model.Type integerValue] == 1)
                {
                    if([model.Count integerValue] > 0)
                    {
                        return;
                    }
                }
            }
            self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
            self.topUpview.delegate = self;
            [self.view addSubview:self.topUpview];
            return;
            
            
        } error:^(NSError *error) {
            self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
            self.topUpview.delegate = self;
            [self.view addSubview:self.topUpview];
            return;
        }];
    }
    if ([self checkCameraAuthorization] && [self checkMicroPhoneAuthorization]) {
        [self cancelMatch];
        if (self.orderList.count > btn.tag) {
            NSDictionary *dic = self.orderList[btn.tag];
            [self grabOrder:dic];
        }
    }
}
//打
- (void)grabOrder:(NSDictionary *)dic {
    [MBProgressHUD showMessage:@"" toView:self.view];
    [[[XLHTTPSessionManager sharedManager] grabOrderWithUserId:F(@"%@", dic[@"UserId"]) anchorId:[[XLAccountManager shareInstance] model].Id matchId:dic[@"MatchId"]] subscribeNext:^(id x) {
        [MBProgressHUD hideHUDForView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self requestOrderListIsPlay:NO];
        });
        NSInteger result = [x[@"result"] integerValue];
        if (result == 0) { //抢单成功，发送自定义消息
            if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
                [self sendGrabOrderCustomMessageWithOrderNum:dic[@"MatchId"] orderUserId:F(@"%@", dic[@"UserId"]) orderNickName:[[XLAccountManager shareInstance] model].NickName orderHeadImg:[[XLAccountManager shareInstance] model].HeadImg];
            } else {
                [self sendGrabOrderCustomMessageWithOrderNum:dic[@"MatchId"] orderUserId:F(@"%@", dic[@"UserId"]) orderNickName:[[XLAccountManager shareInstance] model].NickName orderHeadImg:[[XLAccountManager shareInstance] model].HeadImg];
                @weakify(self);
                [[[XLHTTPSessionManager sharedManager] makeCallWithAnchorId:dic[@"UserId"] userId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
                    @strongify(self);
                    HomeCallModel *model = x;
                    NSString *callID =  F(@"%@", model.CallId);
                    CallMakeViewController *make = [[CallMakeViewController alloc] init];//拔打电话
                    make.IsOneTimeCall = model.IsOneTimeCall;
                    make.UserFreeSecond = model.UserCardSecond;
                    make.peerId = [NSString stringWithFormat:@"%@",dic[@"UserId"]];
                    make.headStr = dic[@"ImgUrl"];
                    make.nickNameStr = dic[@"NickName"];
                    make.ismic = YES;
                    make.iscinema = YES;
                    make.callid = callID;
                    make.videoid = [NSString stringWithFormat:@"%@",callID];
                    make.moneyStr = F(@"%@", [NSDecimalNumber decimalNumberWithString:dic[@"Price"]]);
//                    make.gradeStr = [NSString stringWithFormat:@"%@",dic[@"leval"]];
                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:make animated:YES completion:nil];
                    self.isRequestMatch = NO;
                    [self cancelMatch];
                    
                } error:^(NSError *error) {
                    @strongify(self);
                    [self cancelMatch];
                    NSLog(@"%@", error);
                    if (error.code == 6) {  //余额不足
                        self.topUpview = [[XLNewTopUpView alloc] initWithFrame:self.view.frame withIn_purchase:NO withTopupMonyAry:self.topUpMoneyArr withTopupJDAry:self.topUpJDArr];
                        self.topUpview.delegate = self;
                        [self.view addSubview:self.topUpview];
                        
                    } else if (error.code == -4) {  //被拉入黑名单
                        [HelpTool startTipViewWithText:@"已成为黑名单用户" duration:2.0f type:kTipViewTypeNone];
                    } else if (error.code == -3) {  //对方已屏蔽视聊
                        [HelpTool startTipViewWithText:@"对方取消了视频通话功能" duration:2.0f type:kTipViewTypeNone];
                        IMAMsg *msgs = [IMAMsg chatMsgWithText:@"我想跟你视频聊天，你却不在，你有时间了跟我说下吧"];
                        IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:[NSString stringWithFormat:@"%@",dic[@"UserId"]]];
                        [conversation sendMessage:msgs completion:^(NSArray *imamsgList, BOOL succ, int code) {
                        }];
                    } else {  //创建失败
                        [HelpTool startTipViewWithText:[error.userInfo objectForKey:@"NSLocalizedDescription"] duration:2.0f type:kTipViewTypeNone];
                    }
                }];
            }
        } else if (result == -10001 || result == -10003) {
            NSString *str;
            if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {
                str = @"该用户已经被其他美女抢走了，看看其他用户吧";
            } else {
                str = @"该美女已经被其他用户抢走了，看看其他美女吧";
            }
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"你手慢了" message:str preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDestructive handler:NULL];
            NSAttributedString *atr = [[NSAttributedString alloc] initWithString:str attributes:@{NSForegroundColorAttributeName : HEXCOLOR(0x54545a)}];
            [alert setValue:atr forKey:@"attributedMessage"];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:NULL];
        } else if (result == -10002) {
            if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"]) {
                [MBProgressHUD showContent:@"该美女已经取消了通话，看看其他美女吧" toView:self.view];
                return ;
            }
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"用户已取消通话" message:@"该用户已经取消视频通话，你可以主动邀请他视频聊天哦" preferredStyle:UIAlertControllerStyleAlert];
            NSAttributedString *atr = [[NSAttributedString alloc] initWithString:@"该用户已经取消视频通话，你可以主动邀请他视频聊天哦" attributes:@{NSForegroundColorAttributeName : HEXCOLOR(0x54545a)}];
            
            [alert setValue:atr forKey:@"attributedMessage"];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:NULL];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"邀请他" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                IMAConversation *conversation = [[IMAPlatformxl sharedInstance].conversationMgr chatWith:F(@"%@", dic[@"UserId"])];
                NSDictionary * xmlDic = @{
                                          @"action": @8,
                                          @"imageUrl": [[XLAccountManager shareInstance] model].HeadImg ?: @"",
                                          };
                IMAMsg *msg = [IMAMsg shareToGroupMsgWithCustomDic:xmlDic];
                [conversation sendMessage:msg completion:^(NSArray *imamsglist, BOOL succ, int code) {
                    
                }];
            }];
            [alert addAction:action1];
            [alert addAction:action2];
            [self presentViewController:alert animated:YES completion:NULL];
        } else {
            [MBProgressHUD showContent:x[@"msg"] toView:self.view];
        }
        
    } error:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showContent:@"抢单失败" toView:self.view];
    }];
}

#pragma mark - IM Group
- (void)enterObserveGroup {
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {  //主播
        [[TIMGroupManager sharedInstance] JoinGroup:MatchGroupId1 msg:@"" succ:^{
        } fail:^(int code, NSString *msg) {
        }];
    } else {
        [[TIMGroupManager sharedInstance] JoinGroup:MatchGroupId2 msg:@"" succ:^{
        } fail:^(int code, NSString *msg) {
        }];
    }
}

- (void)exitObserveGroup {
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {  //主播
        [[TIMGroupManager sharedInstance] QuitGroup:MatchGroupId1 succ:^{
        } fail:^(int code, NSString *msg) {
        }];
    } else {
        [[TIMGroupManager sharedInstance] QuitGroup:MatchGroupId2 succ:^{
        } fail:^(int code, NSString *msg) {
        }];
    }
}

- (void)enterMatchGroup {
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {  //主播
        [[TIMGroupManager sharedInstance] JoinGroup:MatchGroupId2 msg:@"" succ:^{
            [self sendNewOrderCustomMessageWithOrderNum:self.matchId];
            self.isRequestMatch = NO;
        } fail:^(int code, NSString *msg) {
            [MBProgressHUD showContent:@"匹配失败，请稍后再试" toView:self.view];
            self.isRequestMatch = NO;
            [self cancelMatch];
        }];
    } else {
        [[TIMGroupManager sharedInstance] JoinGroup:MatchGroupId1 msg:@"" succ:^{
            [self sendNewOrderCustomMessageWithOrderNum:self.matchId];
            self.isRequestMatch = NO;
        } fail:^(int code, NSString *msg) {
            [MBProgressHUD showContent:@"匹配失败，请稍后再试" toView:self.view];
            self.isRequestMatch = NO;
            [self cancelMatch];
        }];
    }
}

- (void)exitMatchGroup {
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {  //主播
        [self sendCancelOrderCustomMessageWithOrderNum:self.matchId completion:^{
            [[TIMGroupManager sharedInstance] QuitGroup:MatchGroupId2 succ:^{
                self.isRequestCancelMatch = NO;
            } fail:^(int code, NSString *msg) {
//                [MBProgressHUD showContent:msg toView:self.view];
                self.isRequestCancelMatch = NO;
            }];
        }];
    } else {
        [self sendCancelOrderCustomMessageWithOrderNum:self.matchId completion:^{
            [[TIMGroupManager sharedInstance] QuitGroup:MatchGroupId1 succ:^{
                self.isRequestCancelMatch = NO;
            } fail:^(int code, NSString *msg) {
//                [MBProgressHUD showContent:msg toView:self.view];
                self.isRequestCancelMatch = NO;
            }];
        }];
    }
}

#pragma mark - Custom IM
- (void)sendNewOrderCustomMessageWithOrderNum:(NSString *)orderNum {
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {  //主播
        [self sendCustomMessageWithOrderNum:orderNum userId:[[XLAccountManager shareInstance] model].Id eventId:1 nickName:[[XLAccountManager shareInstance] model].NickName headImg:[[XLAccountManager shareInstance] model].HeadImg groupId:MatchGroupId2 completion:NULL];
    } else {
        [self sendCustomMessageWithOrderNum:orderNum userId:[[XLAccountManager shareInstance] model].Id eventId:1 nickName:[[XLAccountManager shareInstance] model].NickName headImg:[[XLAccountManager shareInstance] model].HeadImg groupId:MatchGroupId1 completion:NULL];
    }
}

- (void)sendCancelOrderCustomMessageWithOrderNum:(NSString *)orderNum completion:(void (^)(void))completion {
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {  //主播
        [self sendCustomMessageWithOrderNum:orderNum userId:[[XLAccountManager shareInstance] model].Id eventId:2 nickName:[[XLAccountManager shareInstance] model].NickName headImg:[[XLAccountManager shareInstance] model].HeadImg groupId:MatchGroupId2 completion:completion];
    } else {
        [self sendCustomMessageWithOrderNum:orderNum userId:[[XLAccountManager shareInstance] model].Id eventId:2 nickName:[[XLAccountManager shareInstance] model].NickName headImg:[[XLAccountManager shareInstance] model].HeadImg groupId:MatchGroupId1 completion:completion];
    }
}

- (void)sendGrabOrderCustomMessageWithOrderNum:(NSString *)orderNum orderUserId:(NSString *)orderUserId orderNickName:(NSString *)orderNickName orderHeadImg:(NSString *)orderHeadImg {
    if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"1"]) {  //主播
        [self sendCustomMessageWithOrderNum:orderNum userId:orderUserId eventId:3 nickName:orderNickName headImg:orderHeadImg groupId:nil completion:NULL];
        [self sendCustomMessageWithOrderNum:orderNum userId:orderUserId eventId:3 nickName:orderNickName headImg:orderHeadImg groupId:MatchGroupId1 completion:NULL];
    } else {
        [self sendCustomMessageWithOrderNum:orderNum userId:orderUserId eventId:3 nickName:orderNickName headImg:orderHeadImg groupId:nil completion:NULL];
        [self sendCustomMessageWithOrderNum:orderNum userId:orderUserId eventId:3 nickName:orderNickName headImg:orderHeadImg groupId:MatchGroupId2 completion:NULL];
    }
}

- (void)sendCustomMessageWithOrderNum:(NSString *)orderNum userId:(NSString *)userId eventId:(NSInteger)eventId nickName:(NSString *)nickName headImg:(NSString *)headImg groupId:(NSString *)groupId completion:(void (^)(void))completion {
    TIMMessage *msg = [[TIMMessage alloc] init];
    TIMOfflinePushInfo *info = [[TIMOfflinePushInfo alloc] init];
    info.pushFlag = TIM_OFFLINE_PUSH_NO_PUSH;
    [msg setOfflinePushInfo:info];
    TIMCustomElem *elem = [[TIMCustomElem alloc] init];
    NSDictionary *dic;
    if (userId != nil && headImg != nil) {
        if (groupId) {
            dic = @{
                    @"groupId"  : groupId ?: @"",
                    @"orderNum" : orderNum ?: @"",
                    @"hostUserId" : userId,
                    @"event" : @(eventId),
                    @"name" : nickName,
                    @"headimg" : headImg
                    };
        } else {
            dic = @{
                    @"oppositeUserId" : userId ?: @"",
                    @"orderNum": orderNum ?: @"",
                    @"name" : nickName ?: @"",
                    @"headimg" : headImg ?: @"",
                    @"leval" : @"1",
                    @"levalIcon" : @"",
                    @"address" : @"",
                    @"age" : @"",
                    @"job" : @""
                    };
        }
    }
    elem.data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    if (groupId) {
        elem.desc = @"";
        elem.ext = @"CallOrderExt";
    } else {
        elem.desc = @"";
        elem.ext = @"QiangDanNotification";
    }
    
    [msg addElem:elem];
    TIMConversation *con = [[TIMManager sharedInstance] getConversation:groupId ? TIM_GROUP : TIM_C2C receiver:groupId?: userId];
    [con sendOnlineMessage:msg succ:^{
        if (completion) {
            completion();
        }
    } fail:^(int code, NSString *msg) {
//        [MBProgressHUD showContent:msg toView:self.view];
        if (completion) {
            completion();
        }
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _orderList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XLMatchOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLMatchOrderTableViewCell class]) forIndexPath:indexPath];
    if (self.orderList.count > indexPath.row) {
        NSDictionary *dic = self.orderList[indexPath.row];
        [cell.avatarImageView setImageWithURL:[NSURL URLWithString:dic[@"ImgUrl"]] placeholder:nil];
        [cell.levelImage setImageWithURL:[NSURL URLWithString:dic[@"LevelIcon"]] placeholder:nil];
        cell.nickNameLabel.text = dic[@"NickName"];
        if ([[[XLAccountManager shareInstance] model].IsAnchor isEqualToString:@"0"]) {
            cell.detailLabel.text = F(@"%@金豆/分钟", [NSDecimalNumber decimalNumberWithString:dic[@"Price"]]);
        }
        [cell.dialButton addTarget:self action:@selector(dialAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.dialButton.tag = indexPath.row;
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
            cell.detailLabel.hidden = YES;
        }
    }else{
        
        cell.hidden = YES;
    }
    return cell;
}

- (UIImage*) buttonImageFromColors:(NSArray*)colors frame:(CGRect)frame {
    NSMutableArray *ar = [NSMutableArray array];
    for(UIColor *c in colors) {
        [ar addObject:(id)c.CGColor];
    }
    UIGraphicsBeginImageContextWithOptions(frame.size, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
    CGPoint start;
    CGPoint end;
    start = CGPointMake(0.0, 0.0);
    end = CGPointMake(frame.size.width, 0.0);
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    if (!isAvalible) {
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [[UIViewController topViewController] presentViewController:alert animated:YES completion:NULL];
        
    }
    return isAvalible;
}

- (BOOL)checkMicroPhoneAuthorization {
    BOOL isAvalible = YES;
    isAvalible = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio] == AVAuthorizationStatusAuthorized;
    if (!isAvalible) {
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的麦克风权限，无法进行录音。可以在手机 > 设置 > 隐私 > 麦克风中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [[UIViewController topViewController] presentViewController:alert animated:YES completion:NULL];
    }
    return isAvalible;
}

-(void)MakeData
{
    [BMHHTTPSession GETBMHVideo:@"/api/v1/VideoChatInfo/GetRechareInfo" paraments:@{@"type":@"1"} success:^(id  _Nullable JSON) {
        NSLog(@"接口返回充值金额:%@",JSON);
        if ([[UserDefaults objectForKey:XiangLove_IsSH] boolValue]  == YES) {
            self.topUpMoneyArr = [NSMutableArray arrayWithObjects:@"6",@"30",@"50",@"108",nil];
            self.topUpJDArr    = [NSMutableArray arrayWithObjects:@"42",@"210",@"350",@"756",nil];
            self.myMoney       = self.topUpMoneyArr[0];
        }else{
            [self getTopupList:JSON[@"data"]];
        }
    } failure:^(NSError * _Nullable error) {
        NSLog(@"%@", error);
        if ([[UserDefaults objectForKey:XiangLove_IsSH] boolValue]  == YES) {
            self.topUpMoneyArr = [NSMutableArray arrayWithObjects:@"6",@"30",@"50",@"108",nil];
            self.topUpJDArr    = [NSMutableArray arrayWithObjects:@"42",@"210",@"350",@"756",nil];
            self.myMoney       = self.topUpMoneyArr[0];
        }else{
            self.topUpMoneyArr = [NSMutableArray arrayWithObjects:@"30",@"50",@"100",@"500", nil];
            self.topUpJDArr    = [NSMutableArray arrayWithObjects:@"300",@"500",@"1000",@"5000",nil];
            self.myMoney       = self.topUpMoneyArr[0];
        }
    }];
}

-(void)getTopupList:(NSMutableArray *)arr
{
    for (int i = 0; i < arr.count; i++) {
        
        XLTopUpModel * topupMd = [XLTopUpModel modelWithDictionary:arr[i]];
        [self.topUpMoneyArr addObject:topupMd.money];
        [self.topUpJDArr    addObject:topupMd.jindou];
        if (i == 0) {
            self.myMoney = topupMd.money;
        }
    }
    
}

#pragma mark -XLNewTopUpDelegate
-(void)XLSelectedJD:(UIButton *)selectedBtn
{
    
    self.myMoney = [self.topUpMoneyArr objectAtIndex:selectedBtn.tag];
    BMHLog(@"选择了%@",self.myMoney);
}

-(void)XLNewtestTopup
{
    self.myMoney = @"1";
}

#pragma mark - 微信充值
-(void)XLNewWXZHIFU:(UIButton *)wxBtn;
{
    
    if (!([self.myMoney integerValue] > 0)) {
        
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
        
    } else {
//        [self analyticsEvent9];
        [[WeixinHelper sharedWeixinHelper] getUrlWithWXMoney:self.myMoney Months:@"0" TranstypeId:@"1" RemarksInfo:RemarksRose KKOrder:@"" kkUserid:@""];
        
        self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
    }
}


#pragma mark - 支付宝支付
-(void)XLNewZFBZHIFU:(UIButton *)zfbBtn;
{
    
    if (!([self.myMoney integerValue] > 0)) {
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
    } else {
//        [self analyticsEvent7];
        self.actionType = @"1";
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[[XLHTTPSessionManager sharedManager] getZFBPlayOrder:[[XLAccountManager shareInstance] model].Id giftId:@"1" TransType:self.actionType payType:@"4" FeeType:@"" Money:self.myMoney PrivateInfo:zhf_PrivateKey Remarks:RemarksRose Months:@"0" secretKey:[[XLAccountManager shareInstance] model].SecretKey] subscribeNext:^(id x) {
            BMHLog(@"===支付宝创建订单===%@",x);
            NSString * success = [NSString stringWithFormat:@"%@",x[@"success"]];
            self.payorder      = [NSString stringWithFormat:@"%@",x[@"data"]];
            if ([success isEqualToString:@"0"]) {
                NSString *money = [NSString stringWithFormat:@"%.2f", [self.myMoney floatValue]];
//                [ZhifuHelp InPutzhifubaoWithDingdan:self.payorder Money:money subjesct:RemarksRose body:RemarksRose successBlock:^{
//                    
//                    [self.navigationController popViewControllerAnimated:YES];
//                    
//                } failBlock:^{
//                    
//                    [self.navigationController popViewControllerAnimated:YES];
//                }];
                
                self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
                
            } else {
                self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
                [HelpTool startTipViewWithText:@"创建订单失败" duration:1.0 type:kTipViewTypeNone];
            }
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            
        } error:^(NSError *error) {
            NSLog(@"错误:%@",error);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [MBProgressHUD showContent:@"加载失败,请重试!" toView:self.view];
            
        }];
    }
}

#pragma mark - AppstorePay(内购)
-(void)xlAppstorePay:(UIButton *)payBtn
{
    [self hadenlTopUpIn_purchase:payBtn];
}

#pragma mark - AppStore内购支付订单
- (void)hadenlTopUpIn_purchase:(UIButton *)sender {
    if (!([self.myMoney integerValue] > 0)) {
        [HelpTool startTipViewWithText:@"请选择你需要的金额!" duration:1.5 type:kTipViewTypeNone];
    } else {
        
        self.actionType = @"1";
        [MBProgressHUD showMessage:nil];
        NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:UserID];
        NSDate *now = [NSDate date];
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = kBMHRequestTimeFormat;
        //时间戳
        NSString *sTime = [fmt stringFromDate:now];
        NSString *objID = @"0";
        NSString *publicKey = @"BMH2014YDYWB";
        NSString *actionType = self.actionType;
        NSString *nat = [NSString stringWithFormat:@"%@%@%@%@%@",objID, uid, publicKey, actionType, sTime];
        nat = [nat md5Encrypt];
        NSDate * senddate=[NSDate date];
        NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"YYYY-MM-dd_HH:mm"];
        NSString *locationString = [dateformatter stringFromDate:senddate];
        
        self.zfbDic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"Type",uid,@"Userid",@"1",@"Giftid",self.actionType,@"Transtype",@"6",@"Paytype",@"",@"Feetype",self.myMoney,@"Money",zhf_PrivateKey,@"Privateinfo",RemarksRose,@"Remarks",@"0",@"Months",locationString,@"Timestamp",nat,@"Appsign",kAppTypeOrId,@"appid",KAPPFr,@"qudao",nil];
        
        [BMHHTTPSession GET:@"/MobileInterface/Pay/AliPay.ashx" paraments:self.zfbDic success:^(id  _Nullable JSON) {
            NSLog(@"===苹果内购创建订单===%@",JSON);
            NSString *errcode = JSON[@"result"][@"errcode"];
            self.payorder = JSON[@"result"][@"OrderNo"];
            if ([errcode isEqualToString:@"0"]) {
                self.productIds= [NSString stringWithFormat:@"xnjy%@",self.myMoney];
                if([SKPaymentQueue canMakePayments])
                {
                    //buy AppStore Products
                    [[BMHStoreObserver sharedInstance] buy:self.productIds withPayMonyNum:self.myMoney andPayOrder:self.payorder];
                    self.myMoney = [self.topUpMoneyArr objectAtIndex:0];
                    
                }else
                {
                    BMHLog(@"不允许程序内付费");
                }
                
            } else {
                
                [HelpTool startTipViewWithText:@"创建订单失败" duration:1.0 type:kTipViewTypeNone];
            }
            
            [MBProgressHUD hideHUD];
        } failure:^(NSError * _Nullable error) {
            [MBProgressHUD hideHUD];
        }];
    }
}
@end
